<template>
  <div id="cone-container"></div>
</template>

<script>
  import * as THREE from 'three'
  import OrbitControls from 'threejs-orbit-controls'

  export default {
    name: "Cone3D",
    mounted() {
      let scene = new THREE.Scene();
      scene.background = new THREE.Color(0xf0f0f0)
      var axes = new THREE.AxesHelper(100)
      scene.add(axes)
      var camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 10000);
      var controls = new OrbitControls(camera);

      var raycaster = new THREE.Raycaster();
      var mouse = new THREE.Vector2();

      var renderer = new THREE.WebGLRenderer();


      renderer.setSize(4*window.innerWidth / 5, window.innerHeight);
      document.getElementById('cone-container').appendChild(renderer.domElement)


      var conegeometry = new THREE.CylinderGeometry(3, 5, 10, 32);
      var conematerial = new THREE.MeshNormalMaterial({
        vertexColors: THREE.VertexColors,
        flatShading: true
      });
      var cone = new THREE.Mesh(conegeometry, conematerial);

      scene.add(cone)

      camera.position.set(20, 10, 150);
      controls.update();


      var animate = function () {
        requestAnimationFrame(animate);
        // 通过摄像机和鼠标位置更新射线
        cone.rotation.x += 0.01;
        cone.rotation.y += 0.01;
        controls.update();
        renderer.render(scene, camera);
      };

      function onMouseMove(event) {
        event.preventDefault();
        mouse.x = ((event.clientX - renderer.domElement.getBoundingClientRect().left) / renderer.domElement.offsetWidth) * 2 - 1;
        mouse.y = -((event.clientY - renderer.domElement.getBoundingClientRect().top) / renderer.domElement.offsetHeight) * 2 + 1;

        raycaster.setFromCamera(mouse, camera);

        // 计算物体和射线的焦点
        let intersects = raycaster.intersectObjects(scene.children);
        for (var i = 0; i < intersects.length; i++) {
          intersects[i].object.material.color.set(0x6699ff);
        }
      }

      window.addEventListener('click', onMouseMove, false);
      requestAnimationFrame(animate)
    }
  }
</script>

<style scoped>

</style>
